import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import store from '@/store'

Vue.use(Router)

const login = r => require.ensure([], () => r(require('@/page/login')), 'login');
const manage = r => require.ensure([], () => r(require('@/page/manage')), 'manage');
const home = r => require.ensure([], () => r(require('@/page/home')), 'home');
const roleList = r => require.ensure([], () => r(require('@/page/system/roles/index')), 'roleList');
const userList = r => require.ensure([], () => r(require('@/page/system/users/index')), 'userList');
const saleOrder = r => require.ensure([], () => r(require('@/page/sales/order/index')), 'saleOrder');
const saleReturn = r => require.ensure([], () => r(require('@/page/sales/return/index')), 'saleReturn');
const saleReserve = r => require.ensure([], () => r(require('@/page/sales/reserve/index')), 'saleReserve');
const purchaseOrder = r => require.ensure([], () => r(require('@/page/purchase/order/index')), 'purchaseOrder');
const purchaseReturn = r => require.ensure([], () => r(require('@/page/purchase/return/index')), 'purchaseReturn');
const purchaseReserve = r => require.ensure([], () => r(require('@/page/purchase/reserve/index')), 'purchaseReserve');
const customerList = r => require.ensure([], () => r(require('@/page/cooperate/customer/index')), 'customerList');
const supplierList = r => require.ensure([], () => r(require('@/page/cooperate/supplier/index')), 'supplierList');
const expensesList = r => require.ensure([], () => r(require('@/page/expenses/index')), 'expensesList');
const productList = r => require.ensure([], () => r(require('@/page/products/index')), 'productList');
const businessCount = r => require.ensure([], () => r(require('@/page/statistics/businessCount')), 'businessCount');
const customerSales = r => require.ensure([], () => r(require('@/page/statistics/customerSales')), 'customerSales');
const supplierBuy = r => require.ensure([], () => r(require('@/page/statistics/supplierBuy')), 'supplierBuy');
const productsAnalysis = r => require.ensure([], () => r(require('@/page/statistics/productsAnalysis')), 'productsAnalysis');
const expenditure = r => require.ensure([], () => r(require('@/page/statistics/expenditure')), 'expenditure');
const commission = r => require.ensure([], () => r(require('@/page/statistics/commission')), 'commission');
const stock = r => require.ensure([], () => r(require('@/page/statistics/stock')), 'stock');
const stockwarning = r => require.ensure([], () => r(require('@/page/statistics/stockwarning')), 'stockwarning');
const personCenter = r => require.ensure([], () => r(require('@/page/common/personCenter')), 'personCenter');
const buyPackage = r => require.ensure([], () => r(require('@/page/common/buyPackage')), 'buyPackage');
const wxPay = r => require.ensure([], () => r(require('@/page/common/wxPay')), 'wxPay');
const todoList = r => require.ensure([], () => r(require('@/page/common/todoList')), 'todoList');
const setPrint = r => require.ensure([], () => r(require('@/page/common/setPrint')), 'setPrint');
const receiveOrder = r => require.ensure([], () => r(require('@/page/cooperate/receiveOrder/index')), 'receiveOrder');
const payOrder = r => require.ensure([], () => r(require('@/page/cooperate/payOrder/index')), 'payOrder');
const joinSplit = r => require.ensure([], () => r(require('@/page/products/joinSplit/index')), 'joinSplit');
const stockTaking = r => require.ensure([], () => r(require('@/page/products/stockTaking/index')), 'stockTaking');
const flowRecords = r => require.ensure([], () => r(require('@/page/statistics/flowRecords')), 'flowRecords');
const customerCheck = r => require.ensure([], () => r(require('@/page/statistics/customerCheck')), 'customerCheck');
const supplierCheck = r => require.ensure([], () => r(require('@/page/statistics/supplierCheck')), 'supplierCheck');
const redirectPage = r => require.ensure([], () => r(require('@/page/common/redirectPage')), 'redirectPage');
const shouldPay = r => require.ensure([], () => r(require('@/page/statistics/shouldPay')), 'shouldPay');
const units = r => require.ensure([], () => r(require('@/page/products/units/index')), 'units');
const priceLevel = r => require.ensure([], () => r(require('@/page/products/priceLevel/index')), 'priceLevel');
const batchQuery = r => require.ensure([], () => r(require('@/page/statistics/batchQuery')), 'batchQuery');
const qualityQuery = r => require.ensure([], () => r(require('@/page/statistics/qualityQuery')), 'qualityQuery');

const routes = [
	{
		path: '/login',
		component: login
	},
	{
		path: '/buyPackage',
		component: buyPackage
	},
	{
		path: '/wxPay',
		component: wxPay
	},
	{
		path: '/manage',
		component: manage,
		name: '',
		children: [{
			path: '',
			component: home,
			meta: [],
		},{
			path: '/redirectPage',
			component: redirectPage,
			meta: [],
		},{
			path: '/roleList',
			component: roleList,
			meta: ['系统管理', '角色管理'],
		},{
			path: '/userList',
			component: userList,
			meta: ['系统管理', '用户管理'],
		},{
			path: '/saleOrder',
			component: saleOrder,
			meta: ['销售', '销售开单'],
		},{
			path: '/saleReturn',
			component: saleReturn,
			meta: ['销售', '销售退货'],
		},{
			path: '/saleReserve',
			component: saleReserve,
			meta: ['销售', '销售预定'],
		},{
			path: '/purchaseOrder',
			component: purchaseOrder,
			meta: ['采购', '采购进货'],
		},{
			path: '/purchaseReturn',
			component: purchaseReturn,
			meta: ['采购', '采购退货'],
		},{
			path: '/purchaseReserve',
			component: purchaseReserve,
			meta: ['采购', '采购预定'],
		},{
			path: '/customerList',
			component: customerList,
			meta: ['客户'],
		},{
			path: '/supplierList',
			component: supplierList,
			meta: ['供货商'],
		},{
			path: '/receiveOrder',
			component: receiveOrder,
			meta: ['财务', '收款单'],
		},{
			path: '/payOrder',
			component: payOrder,
			meta: ['财务', '付款单'],
		},{
			path: '/expensesList',
			component: expensesList,
			meta: ['财务', '日常支出'],
		},{
			path: '/productList',
			component: productList,
			meta: ['商品'],
		},{
			path: '/units',
			component: units,
			meta: ['系统管理', '单位管理'],
		},{
			path: '/priceLevel',
			component: priceLevel,
			meta: ['系统管理', '价格等级'],
		},{
			path: '/joinSplit',
			component: joinSplit,
			meta: ['库存', '组装拆分'],
		},{
			path: '/stockTaking',
			component: stockTaking,
			meta: ['库存', '盘点'],
		},{
			path: '/businessCount',
			component: businessCount,
			meta: ['报表', '经营报表'],
		},{
			path: '/customerSales',
			component: customerSales,
			meta: ['报表', '客户销售汇总'],
		},{
			path: '/supplierBuy',
			component: supplierBuy,
			meta: ['报表', '供货商采购汇总'],
		},{
			path: '/productsAnalysis',
			component: productsAnalysis,
			meta: ['报表', '商品采销分析'],
		},{
			path: '/customerCheck',
			component: customerCheck,
			meta: ['财务', '客户对账单'],
		},{
			path: '/supplierCheck',
			component: supplierCheck,
			meta: ['财务', '供货商对账单'],
		},{
			path: '/expenditure',
			component: expenditure,
			meta: ['报表', '日常收支统计'],
		},{
			path: '/commission',
			component: commission,
			meta: ['报表', '员工提成统计'],
		},{
			path: '/stock',
			component: stock,
			meta: ['库存', '库存查询'],
		},{
			path: '/stockwarning',
			component: stockwarning,
			meta: ['库存', '库存预警'],
		},{
			path: '/batchQuery',
			component: batchQuery,
			meta: ['库存', '批次查询'],
		},{
			path: '/qualityQuery',
			component: qualityQuery,
			meta: ['库存', '保质期查询'],
		},{
			path: '/flowRecords',
			component: flowRecords,
			meta: ['财务', '资金账户流水'],
		},{
			path: '/personCenter',
			component: personCenter,
			meta: ['个人中心'],
		},{
			path: '/todoList',
			component: todoList,
			meta: ['待办'],
		},{
			path: '/setPrint',
			component: setPrint,
			meta: ['打印设置'],
		},]
	}
]

const router = new Router({
	mode: 'hash', // 去掉url中的#
	scrollBehavior: () => ({ y: 0 }),
	routes: routes
})

NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/401', '/404', '/buyPackage']

// 路由拦截
router.beforeEach(async (to, from, next) => {
	NProgress.start();
  
	// 检查 Token
	if (getToken()) {
	  if (to.path === '/login') {
		// 如果访问的是登录页面，重定向到主页
		// next({ path: '/' });
		location.replace(`${window.location.origin}/#/manage`)
		NProgress.done(); // 结束进度条
	  } else {
		// 如果角色信息未加载
		console.log(store.state.roles);
		
		if (store.state.roles.length === 0) {
		  try {
			// 拉取用户信息
			await store.dispatch('GetUserInfo')
			await store.dispatch('GetRoleInfo')
			await store.dispatch('GetPromises')
			// 继续导航到目标路径
			next()
			NProgress.done();
		  } catch (err) {
			await store.dispatch('FedLogOut');
			Message.error(err);
			next({ path: '/' });
			NProgress.done(); // 结束进度条
		  }
		} else {
		  // 如果角色信息已加载，继续导航
		  next(); 
		  NProgress.done(); // 结束进度条
		}
	  }
	} else {
	  // 没有 token
	  if (whiteList.includes(to.path)) {
		next(); // 如果在白名单，直接进入
		NProgress.done(); // 结束进度条
	  } else {
		next({ path: '/login' }); // 否则重定向到登录
		NProgress.done(); // 结束进度条
	  }
	}
  });
  export default router
